package com.tiennt.android.webviewtest;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.EditText;

import com.testPlugin.TestPlugin;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity {
	private EditText txtAddress;
	private Button btnGo;
	private WebView webView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initializeLayout();
		initialViewSetting();
	}

	@SuppressWarnings("deprecation")
	private void initializeLayout() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		int scaleX = displayMetrics.widthPixels / 480, scaleY = displayMetrics.heightPixels / 640;
		Log.v("tiennt", "scale: " + scaleX + "," + scaleY);

		AbsoluteLayout layout = new AbsoluteLayout(this);
		this.setContentView(layout);

		// Edittext: Address bar
		txtAddress = new EditText(this);
		txtAddress.setLayoutParams(new LayoutParams(400 * scaleX, 80 * scaleY,
				0 * scaleX, 0 * scaleY));
		txtAddress.setHint("www.example.com");
		layout.addView(txtAddress);

		// Button: Go
		btnGo = new Button(this);
		btnGo.setLayoutParams(new LayoutParams(80 * scaleX, 80 * scaleY,
				1 + 400 * scaleX, 0 + 0 * scaleY));
		btnGo.setText("Go");
		layout.addView(btnGo);

		// Webview:
		webView = new WebView(this);
		webView.setLayoutParams(new LayoutParams(
				480 * scaleX,
				760 * scaleY,
				1 + 0 * scaleX, 1 + 80 * scaleY));
		webView.loadUrl("file:///android_asset/www/index.html");
		layout.addView(webView);
	}
	
	private void initialViewSetting(){
		btnGo.setOnClickListener(onBtnGoClickListener);
		txtAddress.setOnKeyListener(onTxtAddressKeyListener);
		webView.setWebViewClient(myWebViewClient);
		webView.setWebChromeClient(myWebChromeClient);
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
	}
	
	private View.OnClickListener onBtnGoClickListener = new View.OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
//			loadUrl(txtAddress.getText().toString());
			
		}
	};
	
	private View.OnKeyListener onTxtAddressKeyListener = new View.OnKeyListener() {
		
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			if (keyCode == KeyEvent.KEYCODE_ENTER){
				loadUrl(txtAddress.getText().toString());
				return true;
			}
			return false;
		}
	};
	
	
	private void loadUrl(String address){
		try {
			URL addressURL = new URL(address);
			String host = addressURL.getHost();
			if (host.contains("zing.vn")) {
				// Toast.makeText(getApplicationContext(), "OOPS",
				// Toast.LENGTH_LONG).show();
				webView.loadUrl("file:///android_asset/www/bared.html");
			} else if (host.equals("CallFromJavaScript")){
				// JS call native code
				List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(address), "utf-8"); 
				String function = "", callback = "", content = "", spackage = "";
				for (NameValuePair n: parameters){
					if (n.getName().equals("function")){
						function = n.getValue();
					}
					else if (n.getName().equals("callback")){
						callback = n.getValue();
					}
					else if (n.getName().equals("content")){
						content = n.getValue();
					} else if (n.getName().equals("package")){
						spackage = n.getValue();
					}
				}
				Log.v("TienNT", "Function: " + function);
				Log.v("TienNT", "Callback: " + callback);
				Log.v("TienNT", "Content: " + content);
				new TestPlugin(getApplicationContext()).log(webView, callback, content);
			}else{
				webView.loadUrl(address);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	WebViewClient myWebViewClient = new WebViewClient() {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			loadUrl(url);
			return true;
		}

	};
	
	WebChromeClient myWebChromeClient = new WebChromeClient(){
		public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)   
	    {  
	        new AlertDialog.Builder(MainActivity.this)  
	            .setTitle("Alert")  
	            .setMessage(message)  
	            .setPositiveButton(android.R.string.ok,  
	                    new AlertDialog.OnClickListener()   
	                    {  
	                        public void onClick(DialogInterface dialog, int which)   
	                        {  
	                            result.confirm();  
	                        }  
	                    })  
	            .setCancelable(false)  
	            .create()  
	            .show();  
	          
	        return true;  
	    };  
		public boolean onConsoleMessage(ConsoleMessage cm) {
			Log.d("Console", cm.message() + " -- From line "
                         + cm.lineNumber() + " of "
                         + cm.sourceId() );
			return true;
  }
	};
}
